package cn.z2huo.knowledge.concurrency.threadlocal.timeconsume;

import cn.hutool.core.map.MapUtil;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 *
 * @author z2huo
 */
class SpeedLog {

    private static final ThreadLocal<Map<String, Long>> TIME_RECORD_LOCAL = ThreadLocal.withInitial(SpeedLog::initialStartTime);

    /**
     * 记录调用耗时的本地 Map 变量的初始化方法
     */
    public static Map<String, Long> initialStartTime() {
        LinkedHashMap<String, Long> map = new LinkedHashMap<>(
                MapUtil.DEFAULT_INITIAL_CAPACITY, MapUtil.DEFAULT_LOAD_FACTOR, true);

        long currentTimeMillis = System.currentTimeMillis();
        map.put("start", currentTimeMillis);
        map.put("last", currentTimeMillis);
        return map;
    }

    /**
     * 开始耗时记录
     */
    public static void beginSpeedLog() {
        System.out.println("开始耗时记录");
        TIME_RECORD_LOCAL.get();
    }

    /**
     * 结束耗时记录
     */
    public static void endSpeedLog() {
        TIME_RECORD_LOCAL.remove();
        System.out.println("结束耗时记录");
    }

    public static void printCost() {
        Map<String, Long> map = TIME_RECORD_LOCAL.get();
        map.forEach((k, v) -> System.out.println(k + ": " + v));
        System.out.println("总耗时: " + (map.get("last") - map.get("start")));
    }

    /**
     * 耗时埋点
     */
    public static void logPoint(String point) {

        Map<String, Long> map = TIME_RECORD_LOCAL.get();

        long currentTimeMillis = System.currentTimeMillis();

        // 获取上一次的时间
        Long last = map.get("last");
        // 计算上一次埋点到当前埋点的耗时
        Long cost = currentTimeMillis - last;

        // 保存上一次埋点到当前埋点的耗时
        map.put(point + ", cost", cost);
        // 保存当前时间，供下一次埋点使用
        map.put("last", currentTimeMillis);
    }

}
